from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
# Create your views here.

from .. import models
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import permission_required



@permission_required('myadmin.insert_cates',raise_exception = True)
# 商品分类添加
def catesadd(request):
    if request.method == 'GET':
        # 获取商品的所有分类 以下查询语句是为了将分类商品有序排列先按path排列，再按照id
        data = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
        # data = models.Cates.objects.all()
        # 分配数据
        context = {'cateslist':data}
        return render(request,'myadmin/cates/add.html',context)
    elif request.method == 'POST':
        # print(request.POST.dict())
        try:
            # 执行添加
            ob = models.Cates()
            ob.name = request.POST.get('name')
            ob.pid = request.POST.get('pid')
            # print(ob.pid,type(ob.pid))
            # 添加path,首先需要判断是否是顶级分类，有没有父级
            if ob.pid == '0':
                ob.path='0,'
            else:
                # 如果不是父级分类，就获取所选分类的path
                fob = models.Cates.objects.get(id=ob.pid)
                ob.path = fob.path+ob.pid+','
            ob.save()
            return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_catesindex')+'"</script>')
        except:
            return HttpResponse('<script>alert("添加失败");location.href="'+reverse('myadmin_catesadd')+'"</script>')




@permission_required('myadmin.show_cates',raise_exception = True)
# 商品分类列表
def catesindex(request):

    # 获取所有的数据
    data = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
    data1 = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
    
    # 获取搜索条件和参数
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')
     # 判断是否有搜索条件
    if types:
        # 判断搜索的类型
        if types == 'all':
            from django.db.models import Q
            data = data.filter(name__contains=keywords)
        else:
        # elif types == 'username':
            # data = data.filter(username__contains=keywords)
            # search = {types+'__contains':keywords}
            data = data.filter(pid=str(types))
           
            data = data.filter(name__contains=keywords)




    # 数据分页
    from django.core.paginator import Paginator
    # 实例化分页类　参数１，是获取所有的数据对象　参数２，每页显示多少条
    paginator = Paginator(data,10)

    # 获取当前页码数
    p = request.GET.get('p',1)
    # 获取当前页的数据
    cateslist = paginator.page(p)

    # 分配数据
    context = {'cateslist':cateslist,'data1':data1}
    # 加载模板
    return render(request,'myadmin/cates/index.html',context)


@permission_required('myadmin.del_cates',raise_exception = True)
# 商品分类删除
def catesdel(request):
    # 分类id
    cid = request.GET.get('cid')
    # 获取分类对象
    ob = models.Cates.objects.get(id=cid)
    num = models.Cates.objects.filter(pid=cid).count()
    if num:
        # 有子类，不能删除
        return JsonResponse({'error':1,'msg':'当前类下有子类，不能删除！'})

    # 再确认当前类下是否有商品发布
    data = ob.goods_set.all()
    if data:
        return JsonResponse({'error':1,'msg':'当前类下有商品，不能删除！'})
    # 如果num=0就证明当前分类对象没有子类
    ob = models.Cates.objects.get(id=cid)
    ob.delete()
    return JsonResponse({'error':0,'msg':'删除成功～～～'})

@permission_required('myadmin.edit_cates',raise_exception = True)
# 商品分类修改
def catesedit(request):
    try:
        # 根据ajax请求来的数据获取分类对象
        cid = request.GET.get('cid')
        print(cid)
        ob = models.Cates.objects.get(id=cid)
        ob.name = request.GET.get('name')
        ob.save()
        return JsonResponse({'error':0,'msg':'更新成功！'})
    except:
        return JsonResponse({'error':1,'msg':'更新失败！'})
